﻿using System;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace TestExtensions
{
    public class Summary
    {
        #region Constants

        private const string TIME_REGEX = @"\A(?<month>[0-9]+)\/(?<day>[0-9]+)\/(?<year>[0-9]+) \- (?<hour>[0-9]+)\:(?<minute>[0-9]+)\:(?<second>[0-9]+)\Z";

        #endregion

        #region Variables

        private static Regex _timeMatcher;

        #endregion

        #region Constructors

        static Summary()
        {
            _timeMatcher = new Regex(TIME_REGEX);
        }

        public Summary(XElement elemSummary)
        {
            RunStarted = LoadDate(elemSummary.Attribute("sTime").Value);
            RunEnded = LoadDate(elemSummary.Attribute("eTime").Value);

            var passed = elemSummary.Attribute("passed");
            Passed = (passed != null) ? Convert.ToInt32(passed.Value) : 0;

            var failed = elemSummary.Attribute("failed");
            Failed = (failed != null) ? Convert.ToInt32(failed.Value) : 0;

            var warnings = elemSummary.Attribute("warnings");
            Warnings = (warnings != null) ? Convert.ToInt32(warnings.Value) : 0;
        }

        #endregion

        #region Properties

        public DateTime RunStarted { get; private set; }

        public DateTime RunEnded { get; private set; }
        
        public int Passed { get; private set; }
        
        public int Failed { get; private set; }
        
        public int Warnings { get; private set; }

        #endregion

        #region Methods

        private DateTime LoadDate(string value)
        {
            var match = _timeMatcher.Match(value);
            if (!match.Success)
            {
                throw new Exception("Unable to match the run date.");
            }

            var month = Convert.ToInt32(match.Groups["month"].Value);
            var day = Convert.ToInt32(match.Groups["day"].Value);
            var year = Convert.ToInt32(match.Groups["year"].Value);
            var hour = Convert.ToInt32(match.Groups["hour"].Value);
            var minute = Convert.ToInt32(match.Groups["minute"].Value);
            var second = Convert.ToInt32(match.Groups["second"].Value);

            return new DateTime(year, month, day, hour, minute, second);
        }

        #endregion
    }
}